#include "stdio.h"
#include "stdlib.h"
#include "syscall.h"
#include "atoi.c"

#define PORT 15
#define BUFFERSIZE 512

int main(int argc, char **argv)
{
   int server;
   int n = 0;
   char  message[BUFFERSIZE];
   int limit = 80;
   char receiveBuffer[BUFFERSIZE];
   char rebuiltMessage[BUFFERSIZE];
   int connection = 0;
   char c;
   int counter = 0;
   int z = 0;
   int bytes_read;
   
   if (argc >= 1)
   {
      server = atoi(argv[1]);
   }

   memset(rebuiltMessage, 0, BUFFERSIZE);
   
   //Connect to server

   strcpy(message, "");
   connection = connect(server, PORT);
   if (connection == -1)
   {
      printf("Error connecting to server: %d \n ", connection);
      return -1; 
   }
   else{
      printf("Connected to server.\n");
   }
   //End connect to server


   //Connected receive/send messages
   printf("chat> ");
   while(1)
   {

      // Do we have signal interrupts??
      //printf("Before readline");
      //c = getch();
      
      bytes_read = read(0,&c, 1);

      if (bytes_read == 1){
      printf("%c", c);
      message[counter] = c;

      counter++;
      if (counter == 150){
         c = '\n';
         message[counter] = c;
         printf("\n");
      }
      //printf("After readline");
      //send message

      if ( c == '\n'){
         counter = 0;
         n = write(connection, message, BUFFERSIZE);
         if (n == -1){
            printf("Send error\n");
         }
         else{
           //DEBUG
           printf("chat> ");
           // printf("Sent: %s\n", message);
         }
         if (strcmp(".\n", message) == 0){
            printf("Exiting\n");
            break;
         }
         memset(message, 0, BUFFERSIZE);
      }
      }


   //Receive messages
   n = read(connection, receiveBuffer, BUFFERSIZE);
   if (n == -1){
      printf("Receive error\n");
   }
   else if (n > 0 && strlen(receiveBuffer) > 0){
      //printf("RECEIVED: %s CONNECTIONS: %d LENGTH: %d \n", receiveBuffer, connection, error);
      //printf("RECEIVED: %s CONNECTION: %d LENGTH: %d \n", receiveBuffer, connection, strlen(receiveBuffer));
      strcat(rebuiltMessage, receiveBuffer);
      
      if (receiveBuffer[strlen(receiveBuffer)-1] == '\n'){
         printf("\n%s", rebuiltMessage);
         memset(rebuiltMessage, 0, BUFFERSIZE);
         printf("chat> %s", message);
      }
      //Debug 
      /*
      for (z = 0; z < BUFFERSIZE; z++){
         printf("%c", receiveBuffer[z]);
      }
      printf("\n");
      */
   }
   }

printf("Exiting");

return 0;
}
